<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function binarySearch(nums, target) {
        let start, end;
        let length = nums.length;
        let mid,
          left = 0,
          right = length - 1;
        while (left <= right) {
          mid = left + ((right - left) >> 1);
          if (nums[mid] < target) {
            left = mid + 1;
          } else if (nums[mid] > target) {
            right = mid - 1;
          } else {
            start = mid;
            end = mid;
            for (let i = mid; i >= 0; i--) {
              if (i === 0 || nums[i - 1] !== target) {
                start = i;
                break;
              }
            }
            for (let i = mid; i <= length - 1; i++) {
              if (i === length - 1 || nums[i + 1] !== target) {
                end = i;
                break;
              }
            }
            return [start, end];
          }
        }
        return [-1, -1];
      }
      alert(binarySearch([0, 2, 2], 2));
    </script>
  </body>
</html>
